<template>
<vs-modal :show.sync="showTestResult" effect="fade" width="800px">
  <div class="modal-header" slot='modal-header'>
    <h4 class="modal-title">{{$t('nettest.testResult')}}</h4>
  </div>
  <div class="modal-body" slot='modal-body'>
    <pre id="my-test-show">{{testResultTxt}}</pre>
  </div>
  <div class="modal-footer" slot='modal-footer'>
    <button type="button" class="btn btn-default" @click.prevent="doExitTestResult">{{$t("common.quit")}}</button>
  </div>   
</vs-modal>
<form class="form-horizontal">
  <div class="form-group">
    <label class="control-label"></label>
    <div >
      <p class="form-control-static text-center lead"><strong>{{$t("nettest.netTest")}}</strong></p>
    </div>
  </div>
  <div class="form-group">
    <validator name="form">
      <label class="col-sm-2 control-label">{{$t("nettest.serverAddr")}}</label>
      <div class="col-sm-4">
        <input type="text" class="form-control" :placeholder="$t('nettest.serverIp')" v-model="clientCfg.serverIp" v-validate:clientCfg.serverIp="{ip: true}">
      </div>
    </validator> 
    <validator name="form1"> 
      <label class="col-sm-1 control-label">{{$t("nettest.addrOfTheClient")}}</label>
      <div class="col-sm-4">
        <input type="text" class="form-control" :placeholder="$t('nettest.clientIp')" v-model="clientCfg.clientIp" v-validate:clientCfg.clientIp="{ip: true}">
      </div>
    </validator>
  </div>
  <div class="form-group">
    <label class="col-sm-2 control-label">{{$t("nettest.testType")}}</label>
    <div class="col-sm-9">
      <select class="form-control" v-model="clientCfg.netType">
          <option v-for="option in netTypeOptions">{{option}}</option>
      </select> 
    </div>
  </div>
  <div class="form-group">
    <label class="col-sm-2 control-label">{{$t("nettest.testTime")}}</label>
    <div class="col-sm-9">
      <select class="form-control" v-model="clientCfg.time">
        <option v-for="option in timeOptions" v-bind:value='option.value'>{{option.text}}</option>
      </select>
    </div>
  </div>
  <div class="form-group">
    <label class="col-sm-2 control-label">{{$t("nettest.testBandwidth")}}</label>
    <div class="col-sm-9">
      <select class="form-control" v-model="clientCfg.bandwidth">
        <option v-for='option in bandwidthOptions'>{{option}}</option>
      </select>
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button class="btn btn-default" type="button" @click.prevent="onStartCltTest">{{$t("nettest.startTest")}}</button>
    </div>
  </div>
</form>
</template>

<script>
import isValidIp from "libs/utils.js"
import api from "libs/api.js"
import {http} from 'share/common/api.js'
import async from 'async'
import msgbox from 'libs/msgbox.js'
import locales from './locales.js'
import debugCfg from 'share/debugCfg.js'

export default{
  locales,
  replace: true,
  data: function() {
    return {
      showTestResult: false,
      testResultTxt: '',
      clientCfg: {
        serverIp: '',
        clientIp: '',
        netType: 'tcp',
        time: 20,
        bandwidth: '20M'
      },
      netTypeOptions: ['tcp', 'udp'],
      timeOptions: [{
        text: '10s',
        value: 10
      }, {
        text: '20s',
        value: 20
      }, {
        text: '30s',
        value: 30
      }],
      bandwidthOptions: ['2M', '10M', '20M', '50M', '100M', '300M', '500M', '800M']
    }
  },
  methods: {
    doExitTestResult(){
      this.showTestResult = false
    },
    onStartCltTest(){
      if (this.$form.invalid) {
        this.showState(this.$t('nettest.errorSerAddr'), this.$t('nettest.plzInputAgain'),'error')
        return
      }
      if (this.$form1.invalid) {
        this.showState(this.$t('nettest.errorCliAddr'),this.$t('nettest.plzInputAgain'),'error')
        return
      }
      async.waterfall([
        this.checkSer,
        this.checkClt,
        this.stepLoginSer,
        this.stepLoginClt,
        this.stepCmdSer,
        this.stepCmdClt,
        ],function(err, result){
          this.showState(this.$t('nettest.serviceNotIn'),this.$t('nettest.plzInputAgain'),'warning')
        }.bind(this))
    },
    checkSer(cb){
      http("http://" + this.clientCfg.serverIp + ":8080", '/api/platform/cfg', 'GET', null, {timeout: 1000}).then(function(res){
          if (res && res.data && res.data.code === 0){
            cb(null)
          }
      }.bind(this),function(res){
        this.showState(this.$t('nettest.serviceNotIn'),this.$t('nettest.plzInputAgain'),'warning')
        cb({msg: 'error'})
      }.bind(this))
    },
    checkClt(cb){
      var host="http://" + this.clientCfg.clientIp + ":8080"
      http("http://" + this.clientCfg.clientIp + ":8080", '/api/platform/cfg', 'GET', null, {timeout: 1000}).then(function(res){
          if (res && res.data && res.data.code === 0){
           cb(null)
          }else{
           cb({msg: `code[${res.data.code}]`})
          }
        }.bind(this),function(res){
          this.showState(this.$t('nettest.clientNotIn'),this.$t('nettest.plzInputAgain'),'warning')
          cb()
        }.bind(this))
    },
    stepLoginSer(cb){
      http("http://" + this.clientCfg.serverIp + ":8080",'/api/auth/login', 'POST',{
      username: 'api',
      password: 'api'
      }).then(function(res) {
        if (res && res.data && res.data.code === 0) {
          cb()
        } else {
          cb({msg: `code[${res.data.code}]`})
        }
      }, function(res) {
        cb({msg: 'error'})
      })
    },
    stepLoginClt(cb){
      http("http://" + this.clientCfg.clientIp + ":8080",'/api/auth/login', 'POST',{
      username: 'api',
      password: 'api'
      }).then(function(res) {
        if (res && res.data && res.data.code === 0) {
          cb()
        } else {
          cb({msg: `code[${res.data.code}]`})
        }
      }, function(res) {
        cb({msg: 'error'})
      })
    },
    stepCmdSer(cb){
      var req={
        action: 'runShell',
        paramlist:{
          shName: 'nettstart.sh',
          isBg: 1,
          shArg: '-s -4'
        }
      }
      http("http://" + this.clientCfg.serverIp + ":8080",'/api/common/cmd', 'POST', req).then(function(res)
        {
          if (res && res.data && res.data.code === 0) {
            cb()
          }else{
            cb({msg: `code[${res.data.code}]`})
          }
        }.bind(this),function(res){
            cb({msg: 'error'})
        })
    },
    stepCmdClt(cb){
      var shArg = '-c ' + this.clientCfg.serverIp;
      if (this.clientCfg.netType === 'udp') {
        shArg += ' -u';
      }
      shArg += ' -t ' + this.clientCfg.time;
      shArg += ' -i 5';
      shArg += ' -b ' + this.clientCfg.bandwidth;
      var req = {
        action: 'runShell',
        paramlist:{
          shName: 'nettstart.sh',
          isBg: 1,
          shArg: shArg
        }
      }
      http("http://" + this.clientCfg.clientIp + ":8080", '/api/common/cmd', 'POST', req).then(function(res){
        this.closeTimer = setTimeout(function() {
          swal.close()
          this.getTestResultClt()
          this.onStopTest()
        }.bind(this),(this.clientCfg.time + 1) * 1000)
        this.showTestProcessing(this.$t('alert.plzWait'),this.$t('nettest.underTest'), 'info')
      }.bind(this))
    },
    onStopTest() {
      var req={
        action: 'runShell',
        paramlist:{
          shName: 'nettstop.sh',
          isBg: 0
        }
      }
      http("http://" + this.clientCfg.serverIp + ":8080",'/api/common/cmd', 'POST', req)
      http("http://" + this.clientCfg.clientIp + ":8080",'/api/common/cmd', 'POST', req)
    },
    showState(title, text, type, host){
      msgbox.alert({
        title: title,
        text: text,
        type: type,
        showCancelButton: false,
        confirmButtonColor: "#DD6B55",
        cancelButtonText: this.$t("common.cancel"),
        confirmButtonText: this.$t("common.confirm"),
        closeOnConfirm: false        
      },
      function() {
        setTimeout(function() {
          swal.close()
        }.bind(this), ) 
      }.bind(this))
    },
    showTestProcessing(title, text, type){
      msgbox.alert({
        title: title,
        text: text,
        type: type,
        showCancelButton: false,
        confirmButtonColor: "#DD6B55",
        cancelButtonText: this.$t("common.cancel"),
        confirmButtonText: this.$t("common.stop"),
        closeOnConfirm: false        
      },
      function() {
        var req={
          action: 'runShell',
          paramlist:{
            shName: 'nettstop.sh',
            isBg: 0
          }
        }
        http("http://" + this.clientCfg.serverIp + ":8080",'/api/common/cmd', 'POST', req)
        if (this.closeTimer) {
          clearTimeout(this.closeTimer)
          this.closeTimer = null
        }
        setTimeout(function() {
          console.log('000')
          swal.close()
          this.getTestResultClt()
        }.bind(this), 1*1000)
      }.bind(this))
    },
    getTestResultClt(){
      http("http://" + this.clientCfg.clientIp + ":8080", '/api/storage/file?type=AP&path=/tmp/nettest.txt','GET').then(function(res){
          this.testResultTxt = res.data
          this.showTestResult = true
      }.bind(this));
    }
  },
  ready() {
    if(debugCfg.debugOn) {
      this.clientCfg.serverIp = debugCfg.devIp1
      this.clientCfg.clientIp = debugCfg.devIp2
    }
  }
}

</script>

<style>
body {    
  padding: 50px;
  padding-top: 20px;
}
#my-log-show {
  max-height: 800px;
}
</style>